#! /usr/bin/env python
#coding=utf-8

"""
Create a report from the definition in yaml.
Run over PollyReport [https://github.com/Solomoriah/PollyReports]
"""

import codecs
import yaml
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import landscape, portrait, A4, A5, letter, legal
from PollyReports import *

class SimpleReport(object):

    def __init__(self, filename, data_report):
        self.report = self.load_yaml(filename)
        self.data_report = data_report
        self.rpt = Report(self.data_report)
        self.setting(self.report)

    def load_yaml(self, filename):
        """
        """

        f = codecs.open(filename, encoding='utf-8')
        #f = open(filename)
        report = self.convert(yaml.load(f))
        f.close()
        return report

    def convert(self, d):
        """
        converts strings in python objects
        """
        keys = ['pos', 'font', 'format', 'getvalue']
        for k in d.iterkeys():
            if isinstance(d[k], dict):
                self.convert(d[k])
            else:
                if k in keys:
                    d[k] = eval(d[k])
        return d

    def get_title(self):
        """
        """
        if self.report.has_key('title'):
            return self.report['title']
        else:
            return 'untitled'

    def get_author(self):
        """
        """
        if self.report.has_key('author'):
            return self.report['author']
        else:
            return ''

    def get_pagesize(self):
        """
        """
        values = {'A4':A4,
                'A5':A5,
                'letter':letter,
                'legal':legal,
                'landscape':landscape,
                'portrait':portrait}
        if self.report.has_key('pagesize') and \
                self.report.has_key('layout'):
            layout = values[self.report['layout']]
            size = values[self.report['pagesize']]
            return layout(size)
        else:
            return portrait(A4)

    def setting(self, data_map):
        """
        """
        content = data_map['content']

        if content.has_key('title'):
            band, childbands = self.get_content(content['title']['band'])
            self.rpt.titleband = Band(band, **childbands)


        if content.has_key('pageheader'):
            band, childbands = self.get_content(content['pageheader']['band'])
            self.rpt.pageheader = Band(band, **childbands)

        if content.has_key('groupheaders'):
            groups = []
            for item in content['groupheaders']['bands'].items():
                band = item[1]
                groupheader, childbands = self.get_content(band)
                if band.has_key('getvalue'):
                    d = {'getvalue':band['getvalue']}
                groups.append(Band(groupheader, **d))

            self.rpt.groupheaders = groups

        if content.has_key('detail'):
            band, childbands = self.get_content(content['detail']['band'])
            self.rpt.detailband = Band(band, **childbands)

        if content.has_key('groupfooters'):
            groups = []
            values = {}
            for item in content['groupfooters']['bands'].items():
                band = item[1]
                groupfooter, childbands = self.get_content(band)
                if band.has_key('getvalue'):
                    values['getvalue'] = band['getvalue']
                if band.has_key('newpageafter'):
                    values['newpageafter'] = band['newpageafter']
                groups.append(Band(groupfooter, **values))

            self.rpt.groupfooters = groups

        if content.has_key('pagefooter'):
            band, childbands = self.get_content(content['pagefooter']['band'])
            self.rpt.pagefooter = Band(band, **childbands)

        if content.has_key('reportfooter'):
            band, childbands = self.get_content(content['reportfooter']['band'])
            self.rpt.reportfooter = Band(band, **childbands)



    def get_content(self, band):
        """
        """
        content = []
        childbands = None

        for k in band.keys():
            if isinstance(band[k], dict):
                if k == 'childbands':
                    childbands = []
                    for b in band[k]:
                        mb, cb =self.get_content(band[k][b])
                        childbands.append(Band(mb, **cb))
                else:
                    if band[k]['type'] == 'element':
                        band[k].pop('type')
                        content.append(Element(**band[k]))
                    elif band[k]['type'] == 'sumelement':
                        band[k].pop('type')
                        content.append(SumElement(**band[k]))
                    elif band[k]['type'] == 'image':
                        band[k].pop('type')
                        content.append(Image(**band[k]))
                    elif band[k]['type'] == 'rule':
                        band[k].pop('type')
                        content.append(Rule(**band[k]))

        return content, {'childbands':childbands}



    def save(self, filename):
        """
        """
        canvas = Canvas(filename)
        canvas.setPageSize(self.get_pagesize())
        canvas.setTitle(self.get_title())
        canvas.setAuthor(self.get_author())

        self.rpt.generate(canvas)
        canvas.save()